package com.hxzy.controller.front;

import com.hxzy.common.constans.RedisConstans;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.util.TokenService;
import com.hxzy.common.util.WaimaiThreadLocal;
import com.hxzy.common.vo.R;
import com.hxzy.dto.LoginDTO;
import com.hxzy.service.ContamerService;
import com.hxzy.vo.LoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

@Api(tags = "手机端登录API")
@RestController
@RequestMapping(value = "/app")
public class FrontLoginController {

    @Autowired
    private ContamerService contamerService;

    @Autowired
    private TokenService tokenService;

    /**
     *  自动装配redis
     */
    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "登录")
    @PostMapping(value = "/login")
    public R login(@RequestBody @Valid LoginDTO loginDTO){
        //验证码是否过期或正确
        String redisKey= RedisConstans.getRedisKey(RedisConstans.CAPTCHA_KEY,loginDTO.getUuid());
        //查询redis值是否存在
        Object redisValue = this.redisTemplate.opsForValue().get(redisKey);
        //如果值为null，过期了
        if(Objects.isNull(redisValue)){
            return R.build(AckCode.SMS_CODE_OVERTIME);
        }
        //判断验证码是否正确
        if(!redisValue.toString().equalsIgnoreCase(loginDTO.getCode())){
            //移出验证码
            this.redisTemplate.delete(redisKey);
            return R.build(AckCode.SMS_CODE_WRONG);
        }
        //移出验证码
        this.redisTemplate.delete(redisKey);

        LoginVO loginVO = this.contamerService.login(loginDTO);

        //把loginVO来换取令牌
        String jwtToken=this.tokenService.createJwtToken(loginVO);
        return R.okHasData(jwtToken);
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping(value = "/user/info")
    public R currentLoginVO(){
        LoginVO loginVO = WaimaiThreadLocal.getCurrent();
        return R.okHasData(loginVO);
    }

    @ApiOperation(value = "退出当前系统")
    @PostMapping(value = "/logout")
    public R logout(){
        LoginVO loginVO = WaimaiThreadLocal.getCurrent();
        this.tokenService.removeRedisLoginVO(loginVO.getToken());
        return R.ok();
    }
}
